package cn.itsource.pethome.org.service.impl;

import cn.itsource.pethome.base.service.impl.BaseServiceImpl;
import cn.itsource.pethome.org.domain.Department;
import cn.itsource.pethome.org.mapper.DepartmentMapper;
import cn.itsource.pethome.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;

    @Transactional
    @Override
    public void insert(Department department) {
        //先保存 是为了获取主键id
        departmentMapper.insert(department);
        this.update(department);
    }

    @Transactional
    @Override
    public void update(Department department) {
        //判断父id 是否为null
        if (department.getParent_id() == null) {//顶级
            Long id = department.getId();
            department.setDirPath("/"+id);
        } else {//不是顶级
            //获取到父id
            Long parent_id = department.getParent_id();
            //根据父id查询父亲
            Department parent = departmentMapper.queryOne(parent_id);
            //父级路径
            String dirPath = parent.getDirPath();
            // 记住要加上   /
            dirPath = dirPath + "/" + department.getId();
            //将修改后的dirpath设置回去
            department.setDirPath(dirPath);
        }
        departmentMapper.update(department);
    }

    @Transactional
    @Override
    public void batchDelete(List<Long> ids) {
        departmentMapper.batchDelete(ids);
    }

    @Override
    public List<Department> deptTree() {
        //1.查询全部部门
        //2.找到顶级部门
        List<Department> departments = departmentMapper.queryAll();
        List<Department> firstCourseType = new ArrayList<>();
        for (Department department : departments) {
            //判断是不是顶级
            if(department.getParent_id() == null){
                firstCourseType.add(department);
            }else{
                //3.不是顶级的找自己的爹把自己放进去
                for (Department department2 : departments) {
                    if(department.getParent_id() == department2.getId()){
                        department2.getChildren().add(department);
                    }
                }
            }
        }
        return firstCourseType;


//        List<Department> firstCourseType = departments.stream().filter(department -> {
//            if (department.getParent_id() == null){
//                return true;
//            }
//            return false;
//        }).collect(Collectors.toList());
//        firstCourseType.forEach(System.out::println);
    }
}
